import React, { Component, Fragment } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';
import router from 'umi/router';

import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Card,
  Row,
  Col,
  Select,
  Cascader,
  Button,
  message,
} from 'antd';
import '@ant-design/compatible/assets/index.css';

const { Option } = Select;
const { Item } = Form;

interface AreaFunctionAddProps extends FormComponentProps {
  dispatch: Dispatch;
  detailInfo: any;
  gardenList: any[];
  INITINFO: any;
  location: { query: any };
}

interface AreaFunctionAddState {
  needIdcertify: boolean;
}

@connect(({
  areaFunctionAdd: { detailInfo, gardenList },
  common: { INITINFO },
}: any) => ({
  detailInfo,
  gardenList,
  INITINFO,
}))

class AreaFunctionAddElem extends Component<AreaFunctionAddProps, AreaFunctionAddState> {
  state: AreaFunctionAddState = {
    needIdcertify: true,
  };

  static getDerivedStateFromProps(nextProps: AreaFunctionAddProps) {
    const { detailInfo } = nextProps;
    if (detailInfo.canSending) {
      return {
        needIdcertify: false,
      };
    }
    return null;
  }

  componentDidMount() {
    const {
      location: { query: { id } },
    } = this.props;
    if (id) this.fetchDetailInfo(id);

    this.fetchAction('common/fetchAddressList');
    this.fetchAction('common/fetchGardenType');
  }

  componentDidUpdate(props: any) {
    const {
      location: { query: { id } },
    } = this.props;
    if (id && id !== props.location.query.id) {
      this.fetchDetailInfo(id);
    }
  }

  componentWillUnmount() {
    this.fetchAction('clear');
  }

  fetchDetailInfo = (id: number) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'areaFunctionAdd/fetch',
      payload: { id },
    });
  };

  handleSending = (value: number) => this.setState({ needIdcertify: Boolean(!value) });

  handleValidation = () => {
    const { form: { getFieldValue } } = this.props;
    const info = getFieldValue('areaCodes');

    if (!info) {
      message.error('请先选择省市区');
      return;
    }

    const params = {
      pareaCode: info[0],
      careaCode: info[1],
      dareaCode: info[2],
    };
    this.fetchAction('fetchGarden', params);
  };

  handleSubmit = () => {
    const { form: { validateFieldsAndScroll } } = this.props;
    validateFieldsAndScroll((errors, values) => {
      if (errors) return;

      const params = {
        ...values,
        pareaCode: values.areaCodes[0] || '',
        careaCode: values.areaCodes[1] || '',
        dareaCode: values.areaCodes[2] || '',
      };
      delete params.areaCodes;

      const { location: { query } } = this.props;
      if (query) params.id = query.id;

      this.fetchAction('saveOrUpdate', params);
    });
  };

  fetchAction = (typeName: string, payload: any = {}) => {
    const type = typeName.indexOf('common') >= 0
      ? typeName : `areaFunctionAdd/${typeName}`;
    const { dispatch } = this.props;
    dispatch({ type, payload });
  };

  render() {
    const { needIdcertify } = this.state;
    const {
      form: { getFieldDecorator },
      detailInfo,
      gardenList,
      INITINFO: { addressList, gardenType },
    } = this.props;

    return (
      <Fragment>
        <PageHeader />

        <Card bordered={false} title="编辑区域功能">
          <Col md={8} sm={24}>
            <Form hideRequiredMark className="tableListForm">
              <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
                <Col span={24}>
                  <Item label="　　　　　省市区" colon={false}>
                    {getFieldDecorator('areaCodes', {
                      initialValue: detailInfo.pareaCode && [
                        detailInfo.pareaCode,
                        detailInfo.careaCode,
                        detailInfo.dareaCode,
                      ],
                      rules: [{ required: true, message: '请选择省市区' }],
                    })(<Cascader options={addressList} changeOnSelect placeholder="请选择" />)}
                  </Item>
                </Col>
                <Col span={24}>
                  <Item label="　　　　社区名称" colon={false}>
                    {getFieldDecorator('gardenId', {
                      initialValue: detailInfo.gardenId || 0,
                      rules: [{ required: false, message: '请选择社区名称' }],
                    })(
                      <Select
                        showSearch
                        placeholder="请选择"
                        onFocus={this.handleValidation}
                        filterOption={(input: any, option: any) => option.props.children
                          .toLowerCase().indexOf(input.toLowerCase()) >= 0
                        }
                      >
                        <Option value={0}>请选择</Option>
                        {gardenList.map((item: any) => (
                          <Option value={item.id} key={item.id}>
                            {item.name}
                          </Option>
                        ))}
                      </Select>,
                    )}
                  </Item>
                </Col>
                <Col span={24}>
                  <Item label="　　　　社区类型" colon={false}>
                    {getFieldDecorator('gardenType', {
                      initialValue: detailInfo.gardenType || 0,
                      rules: [{ required: true, message: '请选择社区类型' }],
                    })(
                      <Select placeholder="请选择">
                        <Option value={0}>不限</Option>
                        {gardenType.map((item: any) => (
                          <Option value={item.mCode} key={item.mCode}>{item.codeName}</Option>
                        ))}
                      </Select>,
                    )}
                  </Item>
                </Col>
                <Col span={24}>
                  <Item label="社区柜体寄件功能" colon={false}>
                    {getFieldDecorator('canSending', {
                      initialValue: detailInfo.canSending || 0,
                      rules: [{ required: true, message: '请选择寄件功能' }],
                    })(
                      <Select placeholder="请选择" onChange={this.handleSending}>
                        <Option value={0}>禁用</Option>
                        <Option value={1}>启用</Option>
                      </Select>,
                    )}
                  </Item>
                </Col>
                <Col span={24}>
                  <Item label="　　　寄件实名制" colon={false}>
                    {getFieldDecorator('needIdcertify', {
                      initialValue: detailInfo.needIdcertify || 0,
                      rules: [{ required: true, message: '请选择寄件实名制' }],
                    })(
                      <Select placeholder="请选择" disabled={needIdcertify}>
                        <Option value={0}>禁用</Option>
                        <Option value={1}>启用</Option>
                      </Select>,
                    )}
                  </Item>
                </Col>
                <Col span={24}>
                  <Item label="　　　取件实名制" colon={false}>
                    {getFieldDecorator('pickupIdcertifyMode', {
                      initialValue: detailInfo.pickupIdcertifyMode || 0,
                      rules: [{ required: true, message: '请选择取件实名制' }],
                    })(
                      <Select placeholder="请选择">
                        <Option value={0}>禁用</Option>
                        <Option value={1}>强制实名</Option>
                        <Option value={2}>非强制实名</Option>
                      </Select>,
                    )}
                  </Item>
                </Col>
              </Row>
            </Form>
          </Col>
          <Col span={24}>
            <Button
              type="primary"
              onClick={this.handleSubmit}
            >
              保存
            </Button>
            <Button
              ghost
              type="primary"
              className="marginL16"
              onClick={() => router.goBack()}
            >
              取消
            </Button>
          </Col>
        </Card>
      </Fragment>
    );
  }
}

export default Form.create<AreaFunctionAddProps>()(AreaFunctionAddElem);
